package com.soup.lab.spring.web.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler({MethodArgumentNotValidException.class})
    public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LOGGER.info("参数校验不通过", e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        return errors.get(0).getDefaultMessage();
    }

    @ExceptionHandler({BindException.class})
    public String handleBindException(BindException e) {
        LOGGER.info("参数校验不通过", e);
        FieldError fieldError = e.getBindingResult().getFieldError();
        return fieldError.getDefaultMessage();
    }

    @ExceptionHandler({ValidationException.class})
    public String handleValidationException(ValidationException e) {
        LOGGER.info("参数校验不通过", e);
        return e.getMessage();
    }

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        LOGGER.error("未知异常", e);
        return "系统错误";
    }

}
